<template>
    <div class="addteacher">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <div class="addteacher-top">
                <div class="top-title">
                    <div class="top-titleBox">
                        <p>基础信息</p>
                    </div>
                </div>
                <div class="top-bottom">
                    <div class="formData">
                            <div class="form-name">
                                <el-form-item label="姓名" prop="studentName">
                                    <el-input v-model="ruleForm.studentName" placeholder="请输入姓名"></el-input>
                                </el-form-item>
                                <el-form-item label="性别" prop="gender">
                                    <el-select v-model="ruleForm.gender" placeholder="请选择性别">
                                        <el-option label="男" value="0"></el-option>
                                        <el-option label="女" value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="电话" prop="concact">
                                    <el-input v-model="ruleForm.concact" placeholder="请输入手机号"></el-input>
                                </el-form-item>
                                <el-form-item label="民族" prop="nation">
                                    <el-select v-model="ruleForm.nation" placeholder="请选择民族">
                                    <el-option 
                    v-for="item in Namelist" :key="item.typeId"
                    :label="item.typeName" :value="item.typeName"></el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                            <div class="certificates">
                                <el-form-item label="证件类型" prop="identificationType">
                                    <el-select v-model="ruleForm.identificationType" style='width:130px;' placeholder="请选择证件">
                                        <el-option v-for="(item, index) in typelist"
                                          :key="index"
                                          :label="item.typeName"
                                          :value="item.typeId">
                                          </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="证件号码" prop="idCardNo">
                                    <el-input v-model="ruleForm.idCardNo" style='width:130px;' placeholder="请输入证件号码"></el-input>
                                </el-form-item>
                                <el-form-item label="学号"  prop="studentIds">
                                    <el-input v-model="ruleForm.studentIds" style='width:130px;' placeholder="请输入学号"></el-input>
                                </el-form-item>
                                <div class="dateOfBirth">
                                    <el-form-item label="出生年月" prop="birthday">
                                        <el-date-picker
                                            style='width:140px;'
                                            v-model="ruleForm.birthday"
                                            type="date"
                                            placeholder="选择日期">
                                        </el-date-picker>
                                    </el-form-item>
                                </div>
                            </div>
                            <div class="ferastion">
                                <el-form-item label="父亲" prop="studentFather">
                                    <el-input  v-model="ruleForm.studentFather" placeholder="您父亲名字"></el-input>
                                </el-form-item>
                                <el-form-item label="联系方式" prop="studentFatherPhone">
                                    <el-input v-model="ruleForm.studentFatherPhone" placeholder="请输入联系方式"></el-input>
                                </el-form-item>
                                <el-form-item label="母亲" prop="studentMother">
                                    <el-input v-model="ruleForm.studentMother" placeholder="您母亲名字"></el-input>
                                </el-form-item>
                                <el-form-item label="联系方式" prop="studentMotherPhone">
                                    <el-input v-model="ruleForm.studentMotherPhone" placeholder="请输入联系方式"></el-input>
                                </el-form-item>
                            </div>
                            <div class="NativePlace">
                                <el-form-item label="籍贯" prop="nativeProvince">
                                    <el-select
                                        v-model="ruleForm.nativeProvince"
                                        placeholder="请选择省"
                                        @change="getCity"  
                                       :validate-event="false"
                                      >
                                        <el-option
                                          :label="item.areaName"
                                          :value="item.areaCode"
                                          v-for="(item, index) in provinceList"
                                          :key="index"
                                        >
                                          {{ item.areaName }}
                                        </el-option>
                                      </el-select>
                                                      </el-form-item>
                                                      <el-form-item label="" prop="nativeCity">
                                                          <el-select
                                        v-model="ruleForm.nativeCity"
                                        placeholder="请选择市"
                                        @change="getArea"
                                        :validate-event="false"
                                      >
                                        <el-option
                                          :label="item.areaName"
                                          :value="item.areaCode"
                                          v-for="(item, index) in cityList"
                                          :key="index"
                                        >
                                          {{ item.areaName }}
                                        </el-option>
                                      </el-select>
                                                      </el-form-item>
                                                      <el-form-item label="" prop="addressCounty">
                                                          <el-select
                                        v-model="ruleForm.addressCounty"
                                        placeholder="请选择区"
                                      >
                                        <el-option
                                          :label="item.areaName"
                                          :value="item.areaCode"
                                          v-for="(item, index) in areaList"
                                          :key="index"
                                        >
                                          {{ item.areaName }}
                                        </el-option>
                                      </el-select>
                                                      </el-form-item>
                                                  </div>
                                                  <div class="postalAddress">
                                                      <el-form-item label="通讯地址" prop="addressProvince">
                                                          <el-select
                                        v-model="ruleForm.addressProvince"
                                        placeholder="请选择省"
                                        @change="getCommunicateCityListApi"
                                      >
                                        <el-option
                                          :label="item.areaName"
                                          :value="item.areaCode"
                                          v-for="(item, index) in provinceList"
                                          :key="index"
                                        >
                                          {{ item.areaName }}
                                        </el-option>
                                      </el-select>
                                                      </el-form-item>
                                                      <el-form-item label="" prop="addressCity">
                                                          <el-select
                                        v-model="ruleForm.addressCity"
                                        placeholder="请选择市"
                                        @change="getCommunicateAreaListApi"
                                      >
                                      <el-option
                                          :label="item.areaName"
                                          :value="item.areaCode"
                                          v-for="(item, index) in communicateCityList"
                                          :key="index"
                                        >
                                          {{ item.areaName }}
                                        </el-option>
                                      </el-select>
                                                      </el-form-item>
                                                      <el-form-item label="" prop="nativeCounty">
                                                          <el-select
                                        v-model="ruleForm.nativeCounty"
                                        placeholder="请选择区"
                                      >
                                        <el-option
                                          :label="item.areaName"
                                          :value="item.areaCode"
                                          v-for="(item, index) in communicateareaList"
                                          :key="index"
                                        >
                                          {{ item.areaName }}
                                        </el-option>
                                      </el-select>
                                </el-form-item>
                                <el-form-item label="" prop="postalAddress">
                                    <el-input v-model="ruleForm.postalAddress" placeholder="请输入详细地址"></el-input>
                                </el-form-item>
                            </div> 
                            <div class="ferastion">
                                <el-form-item label="邮箱" prop="email">
                                    <el-input  v-model="ruleForm.email" placeholder="请输入邮箱"></el-input>
                                </el-form-item>
                                <el-form-item label="年级" prop="idgradeType">
                                    <el-select v-model="ruleForm.idgradeType" placeholder="请选年级">
                                        <el-option v-for="(item, index) in typelists"
                                          :key="index"
                                          :label="item.typeName"
                                          :value="item.typeId">
                                          </el-option>
                                    </el-select>
                                </el-form-item>
                            </div>                           
                    </div>
                    <div class="upImg">
                       <el-upload
            class="avatar-uploader"
            action=""
            name="file"
            :show-file-list="false"
            v-loading = "isLoading"
            :on-change="fileChange1"
            :on-success="handleSuccess"
            element-loading-text = "加载中，请稍后..."
            :limit="1"
            ref='upload'
            >
            <!-- <img :src="imageUrl" alt=""> -->
              <img v-show="ruleForm.avatar" :src="ruleForm.avatar" class="avatar" />
              <i v-show="!ruleForm.avatar" class="el-icon-plus avatar-uploader-icon"></i>
              <div class="text" v-if="!ruleForm.avatar">上传头像</div>
          </el-upload>
                        <div class="text">只能上传jpg格式</div>
                    </div>
                </div>
            </div>
            <div class="formBtn">
                <el-form-item>
                    <el-button class="resetBtn" @click="resetForm">取消</el-button>
                    <el-button type="primary" class="submitBtn" @click="submitForm('ruleForm')">确定</el-button>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import {
  getNationApi
} from "@/api/basics/classroom";
import {
  getProvinceListApi,
  getCityListApi,
  getAreaListApi,
} from "../../api/educational/area";
import {
  upLoadImgApi,
} from "@/api/educational/teacherManagement"
import { studentAddApi} from "@/api/educational/student";
export default {
  name: "Addteacher",
  data() {
    return {
      // form表单
      majorOptions: [], // 专业下拉框
      communicateCityList: [], // 通讯地址市
      communicateareaList: [],
      provinceList: [], //  籍贯省数据
      cityList: [],
      areaList: [],
      imageUrl:'',
      isLoading: false,
      ruleForm: {
        nativeProvince: "",
        addressProvince: "",
        nativeCity: "",
        addressCity: "",
        addressCounty: "",
        nativeCounty: "",
        studentName: "",
        idgradeType:'',
        // education:'',
        studentIds: "",
        gender: "",
        nation: "",
        concact:"",
        identificationType: "",
        idCardNo: "",
        birthday: "",
        email:'',
        studentFather: "",
        studentFatherPhone: "",
        studentMother: "",
        studentMotherPhone: "",
        postalAddress: "",
        avatar: ""
      },
      rules: {
        studentName: [{ required: true, message: "请输入姓名" }],
        concact: [
          { required: true, message: "请输入联系方式" },
          {
            validator: function(rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        gender: [{ required: true, message: "请选择性别" }],
        email:[
          { required: true, message: "请输入邮箱" },
          {
            validator: function(rule, value, callback) {
              if (/[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+/.test(value) == false) {
                callback(new Error("请输入正确邮箱"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
          ],
        nation: [{ required: true, message: "请选择民族" }],
        times:[{required: true, message: "请选择时间"}],
        idgradeType: [{ required: true, message: "请选择年级" }],
        // 证件类型
        identificationType: [
          { required: true, message: "请选择证件类型" },
        ],
        birthday:   [{ required: true, message: "请选择年份" }],
        idCardNo: [
          { required: true, message: "请输入证件号码"},
          {
            min: 18,
            max: 18,
            message: "长度在18个字符",
            trigger: "change",
          },
        ],
        studentIds: [{ required: true, message: "请输入学号" }],
        studentFather: [{ required: true, message: "请输入家长名字" }],
        // diamd:[
        //   { required: true, message: "请输入联系方式" },
        //   {
        //     validator: function(rule, value, callback) {
        //       if (/^1[34578]\d{9}$/.test(value) == false) {
        //         callback(new Error("请输入正确的手机号"));
        //       } else {
        //         callback();
        //       }
        //     },
        //     trigger: "blur"
        //   }
        // ],
        studentFatherPhone: [
          { required: true, message: "请输入联系方式" },
          {
            validator: function(rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        studentMother: [{ required: true, message: "请输入家长名字" }],
        studentMotherPhone: [
          { required: true, message: "请输入联系方式" },
          {
            validator: function(rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        nativeProvince:[{ required: true, message: "请选择省" }],
        nativeCity: [{ required: true, message: "请选择市" }],
        addressCounty: [{ required: true, message: "请选择区（县）" }],
        addressProvince: [{ required: true, message: "请选择省" }],
        addressCity: [{ required: true, message: "请选择市" }],
        nativeCounty: [{ required: true, message: "请选择区（县）" }],
        postalAddress: [
          { required: true, message: "请输入详细地址"}
        ]
      },
      // 图片地址

      // table数据
      // 多选数据

      // 多选绑定值
      value1: "",
      typelist: "",
      Namelist:'',
      typelists:'',
    };
  },
  mounted() {
    this.initAddress();
    this.getList();
    this.getNameList()
    this.getLists()
  },
  methods: {
  handleSuccess() {
      this.$refs.upload.clearFiles() //上传成功之后清除历史记录
    },
    fileChange1(files) {
      let formData = new FormData(); 
       formData.append('file', files.raw);
       console.log(files,'----change');
       console.log(this.$refs.upload);
      upLoadImgApi(formData).then((res) => {
          console.log(res.data.url);
          this.ruleForm.avatar = res.data.url
          if(res.code == 200) {
            this.$refs.upload.clearFiles() //上传成功之后清除历史记录
          }
          // file.target.url = ''
          // document.getElementsByName
      });
    },
     beforeAvatarUpload(file) {
       var img = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = img === 'jpg'
      const suffix2 = img === 'png'
      const suffix3 = img === 'jpeg'
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!suffix && !suffix2 && !suffix3) {
          this.$message.error("只能上传图片！");
          return false
      }
      // 可以限制图片的大小
      if (!isLt1M) {
          this.$message.error('上传图片大小不能超过 1MB!');
      }
      return suffix || suffix2 || suffix3
      // console.log(file,'----------file');
      // this.isLoading = true
      // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      // const isLt2M = file.size / 1024 / 1024 < 10;
      // console.log(isLt2M);

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error(`上传头像图片大小不能超过 ${isLt2M}MB!`);
      // }
      // return isJPG && isLt2M;
    },
   // 初始化地址
    initAddress() {
      getProvinceListApi().then(res => {
        console.log(res, "====");
        if (this.isLookInfo === "3" && res.code === 0) {
          setTimeout(() => {
            this.ruleForm.nativeProvince = res.data[0].areaCode;
            this.ruleForm.addressProvince = res.data[0].areaCode;
          }, 10);
        }
        this.provinceList = res.data;
        // 获取市
        getCityListApi(res.data[0].areaCode).then(res => {
          this.cityList = res.data;
          this.communicateCityList = res.data;
          if (this.isLookInfo === "3") {
            this.ruleForm.nativeCity = res.data[0].areaCode;
            this.ruleForm.addressCity = res.data[0].areaCode;   
          }
          // 获取区
          getAreaListApi(res.data[0].areaCode).then(res => {
            this.areaList = res.data;
            this.communicateareaList = res.data;
            if (this.isLookInfo === "3") {
              this.ruleForm.addressCounty = res.data[0].areaCode;
              this.ruleForm.nativeCounty = res.data[0].areaCode;
            }
          });
        });
      });
    },
    getCity(val) {
      getCityListApi(val).then(res => {
        this.cityList = res.data;
        this.ruleForm.nativeCity = res.data[0].areaCode;
        this.getArea(res.data[0].areaCode);
      });
    },
    // 获取区列表
    getArea(val) {
      // 获取区
      getAreaListApi(val).then(res => {
        console.log(res);
        this.areaList = res.data;
        this.ruleForm.addressCounty = res.data[0].areaCode;
      });
    },
    // 通讯地址   市
    getCommunicateCityListApi(val) {
      getCityListApi(val).then(res => {
        this.communicateCityList = res.data;
        this.ruleForm.addressCity = res.data[0].areaCode;
        this.getCommunicateAreaListApi(res.data[0].areaCode);
      });
    },
    
    // 通讯地址   区
    getCommunicateAreaListApi(val) {
      getAreaListApi(val).then(res => {
        console.log(res);
        this.communicateareaList = res.data;
        this.ruleForm.nativeCounty = res.data[0].areaCode;
      });
    },
    async getList(){
     let res=await getNationApi({parentId:139}) 
     this.typelist=res.rows
     },
     async getNameList(){
     let res=await getNationApi({pageNum:1,
        pageSize:56,parentId:69}) 
     this.Namelist=res.rows
     console.log('233',this.Namelist)
     },
     async getLists(){
     let res=await getNationApi({parentId:55}) 
    //  console.log('233',res)
     this.typelists=res.rows
    //  console.log('23',this.typelists)
     },
    // form提交
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        console.log(valid);
        if (valid) {
          let res = await studentAddApi(this.ruleForm);
          console.log(res);
          this.ruleForm = {};

          if (this.$route.route == "kaoshi") {
            this.$router.push("/testManagement/AddExaminationItem");
          } else {
            this.$router.push("/educational/student");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 重置
    resetForm() {
      this.$router.push("/educational/student");
    },

    // 上传图片
    // handleAvatarSuccess(files) {
    //   console.log(files);
    //   Exupdate(files)
    //     .then(res => {
    //       console.log(res);
    //     })
    //     .catch(() => {});
    //   // this.ruleForm.avatar = URL.createObjectURL(files.file);

    // },
// handleAvatarSuccess(res, file) {
//         this.ruleForm.avatar = URL.createObjectURL(file.raw);
//       },
      // beforeAvatarUpload(file) {
      //   const isJPG = file.type === 'image/jpeg';
      //   const isLt2M = file.size / 1024 / 1024 < 2;

      //   if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!');
      //   }
      //   if (!isLt2M) {
      //     this.$message.error('上传头像图片大小不能超过 2MB!');
      //   }
      //   return isJPG && isLt2M;
      // }
    
  }
};
</script>

<style lang="scss" scoped>
.addteacher {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 0 20px;
  .addteacher-top {
    // width: 1240px;
    height: 390px;
    background: #f9f9f9;
    box-shadow: 0 1px 5px #ccc;
    .top-title {
      width: 100%;
      height: 50px;
      padding: 10px;
      box-sizing: border-box;
      // line-height: 50px;
      .top-titleBox {
        height: 30px;
        line-height: 30px;
        border-left: 3px solid #409eff;
        p {
          height: 100%;
          font-size: 16px;
          color: #409eff;
          font-weight: 600;
          margin-left: 30px;
        }
      }
    }
    .top-bottom {
      width: 110%;
      height: 330px;
      display: flex;
      .formData {
        width: 1000px;
        .form-name,
        .education,
        .ferastion,
        .certificates,
        .education,
        .NativePlace,
        .postalAddress {
          display: flex;
          height: 60px;
        }
        ::v-deep .el-form-item .el-form-item__content {
          margin: 0;
        }
        .postalAddress {
          ::v-deep .el-form-item .el-form-item__content {
            margin-left: 0 !important;
            .el-select {
              display: flex;
              .el-input {
                width: 240px;
                margin-right: 10px;
              }
            }
          }
        }
        .NativePlace {
          ::v-deep .el-form-item .el-form-item__content {
            margin-left: 0 !important;
            .el-select {
              display: flex;
              .el-input {
                width: 240px;
                margin-right: 10px;
              }
            }
          }
        }
      }
      .upImg {
        width: 200px;
        height: 200px;
        margin-left: 40px;
        text-align: center;
        background-color: rgb(240, 240, 240);
        ::v-deep .avatar-uploader {
          width: 100%;
          height: 100%;
        }
        ::v-deep.avatar-uploader .el-upload {
          width: 100%;
          height: 100%;
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
        }
        ::v-deep .avatar-uploader .el-upload:hover {
          border-color: #409eff;
        }
        ::v-deep .avatar-uploader-icon {
          width: 100% !important;
          height: 100% !important;
          font-size: 28px;
          color: #8c939d;
          width: 178px;
          height: 178px;
          line-height: 178px;
          text-align: center;
          // position: relative;
        }
        ::v-deep.el-upload__text {
          position: absolute;
          bottom: 55px;
          left: 33%;
          font-size: 18px;
          color: rgb(159, 159, 159);
        }
        .avatar {
          width: 178px;
          height: 178px;
          display: block;
        }
        .text {
          font-size: 14px;
          color: rgb(211, 211, 211);
        }
      }
    }
  }
  .formBtn {
    width: 100%;
    height: 40px;
    margin-top: 50px;
    text-align: center;
    .submitBtn {
      width: 100px;
      height: 30px;
      line-height: 0;
      color: rgb(72, 149, 219) !important;
      border-radius: 18px;
      color: #fff !important;
    }
    .resetBtn {
      width: 100px;
      height: 30px;
      color: #fff;
      line-height: 0;
      border-radius: 18px;
      border: 1px solid rgb(120, 175, 230);
      color: rgb(120, 175, 230);
    }
  }
}
</style>